package panda.query.condition;

import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.struct.Constant;
import panda.query.struct.NullConstant;
import panda.query.tree.QueryTreeNode;
import panda.record.Schema;
import panda.server.Panda;
import panda.syntax.SelectStm;
import panda.transaction.Transaction;

public class SubqueryValue implements ValueExpression {

	private QueryTreeNode tn = null;
	private Constant cacheValue = null;
	public SelectStm statement;

	public SubqueryValue(SelectStm statement){
		this.statement=statement;		
	}

	@Override
	public boolean appliesTo(Schema sch) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Constant asConstant() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean dominates(Attribute attr) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Constant evaluate(Scanner s, Transaction tx) {
		if (tn == null) tn = Panda.getPlanner().executeSubQuery(statement, tx);

		if (statement.subReferring.size() == 0) {
			if (cacheValue == null) {
				Scanner sc = tn.open();

				if (sc.next())				
					for (Attribute a : tn.getSchema().getAllAttributes()) {
						cacheValue = sc.getValue(a);
						break;
					}
				else
					cacheValue = new NullConstant(); 

				sc.close();
			}

			return cacheValue;
		}

		for (AttributeName a : statement.subReferring)
			a.stubValue(s.getValue(a.getAttribute()));

		Scanner sc = tn.open();

		if (sc.next())
			for (Attribute a : tn.getSchema().getAllAttributes()) {
				Constant c = sc.getValue(a);
				sc.close();
				return c;
			}

		return new NullConstant();
	}

	@Override
	public boolean isConstant() {
		// TODO Auto-generated method stub
		return false;
	}

}
